<?php
/**
 * @ClassName: Shoprefundorder
 * @Description: 退款订单
 * @author: gydtrade
 * @Date: 2024-09-09 22:28
 * @Version: V1.0.0
 */

namespace app\admin\controller;

use app\common\logic\OrderLogic;
use app\common\model;
use think\Controller;
use tpext\builder\traits\HasBuilder;

class Shoprefundorder extends Controller
{
    use HasBuilder;

    protected $dataModel;

    protected function initialize()
    {
        parent::initialize();

        $this->dataModel = new model\RefundOrder();
        $this->pageTitle = '退款订单';
        $this->enableField = 'status';
        $this->pagesize = 10;

        $this->selectTextField = '{id}#{nickname}({mobile})';
        $this->selectFields = 'id,nickname,mobile';
        $this->selectSearch = 'username|nickname|mobile';
    }

    /**
     * 构建搜索
     *
     * @return void
     */
    protected function buildSearch()
    {
        $search = $this->search;

        $search->select('member_id', '会员', 3)->dataUrl(url('/admin/member/selectPage'));
        $search->text('order_id', '订单id', 3);
        $search->text('order_sn', '订单号', 3);
        $search->select('status', '状态', 3)
            ->options([0 => '申请中', 1 => '已通过', 2 => '未通过']);

        $search->datetime('start ', '申请时间', 3)->placeholder('起始');
        $search->datetime('end ', '~', 3)->placeholder('截止');
    }

    /**
     * 构建搜索条件
     * @return array
     */
    protected function filterWhere()
    {
        $searchData = request()->get();

        $where = [];
        if (!empty($searchData['member_id'])) {
            $where[] = ['member_id', 'eq', $searchData['member_id']];
        }

        if (isset($searchData['order_id']) && $searchData['order_id'] != '') {
            $where[] = ['order_id', 'like', '%' . $searchData['order_id'] . '%'];
        }

        if (isset($searchData['order_sn']) && $searchData['order_sn'] != '') {
            $where[] = ['order_sn', 'like', '%' . $searchData['order_sn'] . '%'];
        }

        if (isset($searchData['status']) && $searchData['status'] != '') {
            $where[] = ['status', 'eq', $searchData['status']];
        }

        if (!empty($searchData['start'])) {
            $where[] = ['create_time', 'egt', $searchData['start']];
        }

        if (!empty($searchData['end'])) {
            $where[] = ['create_time', 'elt', $searchData['end']];
        }
        return $where;
    }

    /**
     * 构建表格
     *
     * @return void
     */
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        $table->show('id', 'ID');
        $table->show('member', '会员')->to("{member_id}#{member.nickname}");
        $table->show('order_id', '订单id');
        $table->show('order_sn', '订单号');
        $table->show('order_money', '订单金额');
        $table->show('money', '退款金额');
        $table
            ->match('status', '申请状态')
            ->options([0 => "申请中", 1 => "通过", 2 => "拒绝"])
            ->mapClassGroup([[0, 'info'], [1, 'success'], [2, 'danger']]);
        $table->show('admin_id', '管理员id');

        $table->fields('create_times', '申请/修改时间')->with(
            $table->show('create_time', '申请时间'),
            $table->show('update_time', '修改时间')
        )->getWrapper()->addStyle('width:160px');

        foreach ($data as &$d) {
            $d['__hi_edit__'] = $d['status'] == 1;
        }

        $table->sortable('id, create_time');

        $table->getToolbar()
            ->btnRefresh();

        $table->getActionbar()
            ->btnEdit()
            ->btnView()
            ->mapClass([
                'edit' => ['hidden' => '__hi_edit__'],
            ]);
    }

    /**
     * 构建表单
     * @param $isEdit
     * @param $data
     * @return \think\response\Json|\tpext\think\View|void
     */
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;

        if (!$isEdit) {
            $order_id = input('order_id/d');

            $exists = $this->dataModel->where('order_id', $order_id)->find();

            if ($exists) {
                //已经存在申请记录
                $this->builder()->notify('已经存在申请记录');
                $isEdit = 1;
                $this->addText = '编辑';
                $data = $exists;
            } else {
                $order = model\ShopOrder::where('id', $order_id)->find();

                if (!$order) {
                    return $this->builder()->layer()->close(0, '订单信息不存在');
                }

                if ($order['pay_status'] != 1) {
                    return $this->builder()->layer()->close(0, '订单未支付，不能申请退款');
                }

                $data['order_id'] = $order_id;
                $data['member_id'] = $order['member_id'];
                $data['shopOrder'] = $order;
                $data['member'] = $order['member'];
                $data['status'] = -1;
                $data['money'] = $order['order_amount'];
            }
        }

        $form->divider('订单信息');
        $form->hidden('orde_id');
        $form->hidden('id');
        $form->show('member_id', '用户')->to('{val}#{member.nickname}');
        $form->show('order_id', '订单')->to('{val}#{shopOrder.order_sn}');

        $orderGoodsList = model\ShopOrderGoods::where(['order_id' => $data['order_id']])->where('goods_id', '>', 0)->select();

        $form->items('goods_list', '下单产品列表')->required()->dataWithId($orderGoodsList)->with(
            $form->show('goods_name', '产品')->to('{val}(￥{sale_price})'),
            $form->show('goods_num', '数量'),
        )->canNotAddOrDelete()->readonly();

        if ($data['shopOrder'] && $data['shopOrder']['pay_status'] != 0) {
            $form->match('shopOrder.order_amount', '支付金额')->default('---');
            $form->match('shopOrder.pay_time', '支付时间')->default('---');
            $form->match('shopOrder.pay_code', '支付方式')->options(ShopOrder::$pay_codes)->afterOptions(['__default__' => '---']);
            $form->show('shopOrder.transaction_id', '支付流水号')->default('---');
        }

        $form->divider('退货信息');

        $form->textarea('content', '退款理由');

        if ($data["status"] != -1) {
            if ($data['shopOrder'] && $data['shopOrder']['transaction_id']) {
                $form->text('money', '退款金额')->help('审核通过后退款，使用在线支付(微信/支付宝)的才能退，钱原路返回。');
            } else {
                $form->hidden('money')->value(0);
            }
            // 可以选
            $form->radio('status', '状态')
                ->class('radio-warning') //颜色主题
                ->blockStyle() //显示为块状
                ->options([0 => "申请中", 1 => "同意", 2 => "拒绝"])
                ->default(0);
        } else {
            // 不能选
            $data['status__'] = 0;
            $form->hidden('status')->value(0);
            $form->match('status__', '状态')
                ->options([0 => "提交申请"]);
        }

        $form->textarea('admin_remark', '管理员备注');
    }

    /**
     * 保存数据
     * @param $id
     * @return \think\response\Json|\tpext\think\View|void
     */
    private function save($id = 0)
    {
        $data = input();

        try {
            if (!$id) {
                $exists = $this->dataModel->where('order_id', $data['order_id'])->find();

                if ($exists) {
                    //已经存在申请记录
                    $this->error('订单已存在退款申请记录');
                }

                $order = model\ShopOrder::where('id', $data['order_id'])->find();

                $logic = new OrderLogic($order['member_id']);

                $res = $logic->returnOrder($data['order_id'], $order['member_id'], '系统提交退款申请', ['imgs' => '', 'content' => $data['content'] ?: '申请退款']);

                if ($res['code'] != 1) {
                    return $this->builder()->layer()->closeRefresh(0, $res['msg']);
                }
                $id = $this->dataModel->where("order_id", $data['order_id'])->order('id desc')->value('id');
            }

            // 获取申请记录
            $oldData = $this->dataModel->where("id", $id)->find();
            if ($data['status'] == 0) {
                $oldData->save($data);
                return $this->builder()->layer()->closeRefresh(1, '保存成功');
            }

            // 实例化逻辑
            $logic = new OrderLogic($oldData["member_id"]);

            // 处理退款
            $res = $logic->doReturn($id, $data);

            if (!$res["code"]) {
                $this->error($res["msg"]);
            } else {
                return $this->builder()->layer()->closeRefresh(1, $res["msg"]);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

}